package com.zoo.util;

import java.io.Serializable;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;

/**
 * @Email 22582416@qq.com
 * @author 张如利
 * @version 创建时间:2011-5-7下午11:46:27
 */
public class JPAUtil {

	private static EntityManagerFactory emf;

	static {
		emf = Persistence.createEntityManagerFactory("jpa");
	}

	public static EntityManagerFactory getEntityManagerFactory() {
		return emf;
	}

	public static EntityManager getEntityManager() {
		return emf.createEntityManager();
	}

	public static void save(Object entity) {
		EntityManager em = null ;
		try {
			em = JPAUtil.getEntityManager();
			em.getTransaction().begin();
			em.persist(entity);
			em.getTransaction().commit();
		} finally {
			if (em != null) {
				em.close();
			}
		}
	}
	
	public static void update(Object entity) {
		EntityManager em = null ;
		try {
			em = JPAUtil.getEntityManager();
			em.getTransaction().begin();
			em.merge(entity);
			em.getTransaction().commit();
		} finally {
			if (em != null) {
				em.close();
			}
		}
	}
	
	public static void del(Object entity) {
		EntityManager em = null ;
		try {
			em = JPAUtil.getEntityManager();
			em.getTransaction().begin();
			em.remove(entity);
			em.getTransaction().commit();
		} finally {
			if (em != null) {
				em.close();
			}
		}
	}
	
	public static <T> T find(Class<T> clazz,Serializable id){
		EntityManager em = null ;
		try {
			em = JPAUtil.getEntityManager();
			return em.find(clazz, id);
		} finally {
			if (em != null) {
				em.close();
			}
		}
	}
	
	@SuppressWarnings("unchecked")
	public static <T> List<T> find(String jpasql){
		EntityManager em = null ;
		List<T> list = null ;
		try {
			em = JPAUtil.getEntityManager();
			Query query = em.createQuery(jpasql);
			list = query.getResultList();
			return list;
		} finally {
			if (em != null) {
				em.close();
			}
		}
	}
	
	@SuppressWarnings("unchecked")
	public static <T> List<T> find(String jpasql,Object[] params){
		EntityManager em = null ;
		List<T> list = null ;
		try {
			em = JPAUtil.getEntityManager();
			Query query = em.createQuery(jpasql);
			if(params!=null && params.length>0){
				for(int i=0;i<params.length;i++){
					query.setParameter(i+1, params[i]);
				}
			}
			list = query.getResultList();
			return list;
		} finally {
			if (em != null) {
				em.close();
			}
		}
	}
	
	@SuppressWarnings("unchecked")
	public static <T> List<T> findAll(Class<T> clazz){
		EntityManager em = null ;
		List<T> list = null ;
		try {
			em = JPAUtil.getEntityManager();
			Query query = em.createQuery("from "+clazz.getName());
			list = query.getResultList();
			return list;
		} finally {
			if (em != null) {
				em.close();
			}
		}
	}
}
